package com.woniuxy.redis.service.impl;/*
@author houguai
@create 2021-01-13 11:19
*/

import com.woniuxy.redis.entity.Teacher;
import com.woniuxy.redis.mapper.TeacherMapper;
import com.woniuxy.redis.service.TeacherService;
import com.woniuxy.redis.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class TeacherServiceImpl implements TeacherService{

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Cacheable("allTeacher")  //将当前方法得到的数据写入到redis中
    @Override
    public List<Teacher> all() {
        System.out.println("执行service方法");
        //1.去redis中查询是否有数据
        String key = RedisUtil.generate(this,"all",null);
        //2.有直接返回
        if (redisTemplate.hasKey(key)){
            System.out.println("redis中有数据  直接返回");
            return (List<Teacher>) redisTemplate.opsForValue().get(key);
        }
        //3.调用mapper查询数据
         List<Teacher> teachers= teacherMapper.all();
        //4.将数据存放到redis中
        redisTemplate.opsForValue().set(key,teachers);
        return teachers;
    }

    @Override
    public Teacher findById(int id) {
        System.out.println("执行service方法");
        return teacherMapper.findById(id);
    }
    //删除视频   删除findteacherbyid中的指定id（有坑，删除只能全部删除，不能删指定的）
    @CacheEvict(value = "findById",allEntries = true)
    @Override
    public Boolean delById(int id){
        return true;
    }

}
